import { useRef, useState } from 'react';
import { getReaderInfo } from '@src/utils/chat';
import getChatGptAnswer from '@src/apis/get_chatGpt_answer';
import { message } from 'antd';
import { IChatMessage } from '@src/types/chat';
import { useChatState } from '@src/store/chat/hooks';
import { getRedMarkdown } from '@src/utils';

// 获取当前的chatId，使用ref保存，以便每次拿到最新的chatId
export const useChatId = () => {
  const [chatId, setChatId] = useChatState('chatId');

  const chatIdRef = useRef<string>(chatId);

  const onChangeChatId = (chatId: string) => {
    setChatId(chatId);
    chatIdRef.current = chatId;
  };

  return [chatIdRef, onChangeChatId] as [
    typeof chatIdRef,
    typeof onChangeChatId,
  ];
};

export const useSubmit = () => {
  // 答案
  const [answer, setAnswer] = useState('');
  const [loading, setLoading] = useChatState('isFetching');
  const abortController = useRef(new AbortController());

  // 提交数据
  const submit = async (
    value: string,
    historyMessage: Partial<IChatMessage>[],
    onMessageChange: (value: string, isError?: boolean) => void,
    onError?: (errMsg: string) => void,
  ) => {
    abortController.current = new AbortController();
    // 更新消息
    const innnerOnMessage = (value: string, isError = false) => {
      onMessageChange?.(value, isError);
      setAnswer(value);
    };

    // 错误处理
    const innnerOnError = (errMsg: string) => {
      innnerOnMessage(getRedMarkdown(errMsg), true);
      message.error(errMsg);
    };

    setLoading(true);

    // 最终需要提交的数据
    const data = {
      // max_tokens: 1024 * 3,
      messages: [
        ...historyMessage,
        {
          role: 'user',
          content: value,
        },
      ],
    };

    try {
      const resData = await getChatGptAnswer({
        data,
        abortController: abortController, // 用来终止请求
      });

      // 获取stream流
      const reader = resData?.body?.getReader();
      await getReaderInfo(reader, innnerOnMessage, onError || innnerOnError);
    } catch (error: any) {
      // 这里使用error name来判断好点儿
      if ((error?.message || error)?.includes?.('The user aborted a request')) {
        innnerOnMessage(getRedMarkdown('您已主动取消'), true);
        return; // 这种情况不需要抛出错误
      }
      console.log(error, 'error');
      message.error('获取答案失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const abort = () => {
    abortController.current.abort(); // 终止请求
  };

  return { loading, submit, answer, abort } as const;
};
